package com.jeff.huawei.practice;

public class TicTacToeValidator {

    public static boolean isValidBoard(String[][] board) {
        int countX = 0;
        int countO = 0;

        // Count the number of 'X' and 'O'
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j].equals("X")) {
                    countX++;
                } else if (board[i][j].equals("O")) {
                    countO++;
                }
            }
        }

        // Check the number of 'X' and 'O'
        if (countX != countO && countX != countO + 1) {
            return false;
        }

        // Check winning conditions
        boolean xWins = checkWin(board, "X");
        boolean oWins = checkWin(board, "O");

        // If both 'X' and 'O' win, the board is invalid
        if (xWins && oWins) {
            return false;
        }

        // If 'X' wins, then the number of 'X' must be one more than the number of 'O'
        if (xWins && countX != countO + 1) {
            return false;
        }

        // If 'O' wins, then the number of 'X' must be equal to the number of 'O'
        if (oWins && countX != countO) {
            return false;
        }

        return true;
    }

    private static boolean checkWin(String[][] board, String player) {
        // Check rows and columns
        for (int i = 0; i < 3; i++) {
            if (board[i][0].equals(player) && board[i][1].equals(player) && board[i][2].equals(player)) {
                return true; // Row win
            }
            if (board[0][i].equals(player) && board[1][i].equals(player) && board[2][i].equals(player)) {
                return true; // Column win
            }
        }

        // Check diagonals
        if (board[0][0].equals(player) && board[1][1].equals(player) && board[2][2].equals(player)) {
            return true; // Diagonal win from top-left to bottom-right
        }
        if (board[0][2].equals(player) && board[1][1].equals(player) && board[2][0].equals(player)) {
            return true; // Diagonal win from top-right to bottom-left
        }

        return false;
    }

    public static void main(String[] args) {
        String[][] board = {
            {"X", "O", "X"},
            {" ", "X", " "},
            {"O", " ", "O"}
        };

        if (isValidBoard(board)) {
            System.out.println("The board is valid.");
        } else {
            System.out.println("The board is invalid.");
        }
    }
}
